<script lang="ts" setup>
import type { SubBillItem } from '@/types/api/order'
import type { Ref } from 'vue'
import { orderApi } from '@/request/api'
import { useAppConfig, useProfile } from '@/stores'
import { useConsole, useDayjsFormat, useHideLoading, useLoading, useRouteGuard } from '@/utils'
import { useAliPay } from '@/utils/pay'
import { onLoad, onPullDownRefresh, onShow } from '@dcloudio/uni-app'
import { to } from 'await-to-js'
import { isEmpty } from 'lodash-es'
import { ref } from 'vue'
import { object as zobject, string as zstring } from 'zod'

const appConfig = useAppConfig()
const profile = useProfile()
const oid = ref() as Ref<number>
const bid = ref() as Ref<number>
const dataList = ref<SubBillItem[]>([])

onLoad(async (query) => {
  const zparse = zobject({
    oid: zstring().regex(/^\d+$/).transform(Number),
    bid: zstring().regex(/^\d+$/).transform(Number),
  }).safeParse(query)
  if (!zparse.success) {
    return await useRouteGuard()
  }
  oid.value = zparse.data.oid
  bid.value = zparse.data.bid

  await getList()
})

onShow(async () => {
  if (!isEmpty(dataList.value)) {
    await getList()
  }
})

onPullDownRefresh(async () => {
  await getList()
  uni.stopPullDownRefresh()
})

async function getList() {
  const [err, res] = await to(orderApi.recordPeriodList([bid.value]))
  if (err) {
    return
  }

  dataList.value = res[bid.value]
}

async function handlePay(item: SubBillItem, index: number) {
  useLoading(true)
  const [apiErr, apiRes] = await to(orderApi.newTradePay({
    objId: item.id,
    subject: `分期支付 第${index}期`,
    totalAmount: item.payMoney,
    type: 1,
    buyerId: profile.userInfo.zfbUserId,
  }))
  useHideLoading()
  if (apiErr) {
    return
  }

  // #ifdef MP-ALIPAY
  await to(useAliPay({ tradeNO: apiRes.trade_no }))
  // #endif

  await getList()
}

function handleConsole(item: SubBillItem) {
  useConsole?.log(item)
}
</script>

<template>
  <view v-if="!isEmpty(dataList)" class="px-30px pt-20px safe-pb-20px">
    <template v-for="(item, i) in dataList" :key="i">
      <view class="rd-16px bg-white" :class="{ 'mt-10px': i !== 0 }">
        <!--  -->
        <view class="px-10px pt-10px" @longpress="handleConsole(item)">
          <view class="flex rd-full px-20px text-24px" :class="['bg-#FFF5EB', 'bg-#F4F5F9', 'bg-#F4F5F9'][item.status]">
            <view class="text-#3 lh-50px">第&thinsp;{{ i + 1 }}&thinsp;期</view>
          </view>
        </view>
        <!--  -->
        <view class="pb-50px pt-60px text-center text-36px text-#3">本期还款 ￥{{ item.payMoney }}</view>
        <!--  -->
        <view class="flex items-center justify-between px-22px pb-20px">
          <template v-if="item.status === 0">
            <!--  -->
            <view class="flex flex-col items-start">
              <view class="relative pb-5px">
                <view class="flex-start flex b-2px b-#e4 rd-full b-solid">
                  <view class="h-30px w-30px flex">
                    <view class="i-ri:error-warning-line text-theme-primary m-a text-18px"></view>
                  </view>
                  <view class="text-theme-primary py-6px pr-10px text-18px">亲记得按时还款以免忘记</view>
                </view>
                <view class="absolute bottom-0 left-35px h-10px w-10px rotate-45deg b-2px b-#e4 b-solid b-l-none b-t-none bg-white">
                </view>
              </view>
              <view class="mt-5px flex text-24px">
                <view class="text-#6a">交租日期：</view>
                <view class="text-#3">{{ useDayjsFormat(item.planTime, 'DD') }}&thinsp;之前</view>
              </view>
            </view>
            <!--  -->
            <view class="flex">
              <view v-if="!appConfig.hidePayBtn" class="btn-primary-black w-160px text-26px lh-60px" @click="handlePay(item, i)">点击交租</view>
            </view>
          </template>
          <template v-else>
            <view class="flex text-24px">
              <view class="text-#6a">交租日期：</view>
              <view class="text-#3">{{ useDayjsFormat(item.realPayTime, 'DD') }}</view>
            </view>
            <view class="flex items-center">
              <view
                class="text-30px" :class="{
                  'i-ri:checkbox-circle-fill text-#60CC84': item.status === 1,
                  'i-ri:error-warning-fill text-gray-500': item.status === 2,
                }"
              ></view>
              <view class="ml-5px text-24px text-#6">{{ ['', '已交租金', '已退租金'][item.status] }}</view>
            </view>
          </template>
        </view>
      </view>
    </template>
  </view>
  <view v-else class="px-30px py-20px">
    <view class="h-300px rd-16px bg-white"></view>
    <view class="mt-10px h-300px rd-16px bg-white"></view>
    <view class="mt-10px h-300px rd-16px from-white to-transparent bg-gradient-to-b"></view>
  </view>
</template>

<style lang="less" scoped></style>
